#!/usr/bin/env python
#
#This module contains data and tables classes
#
import re
class AbsRecord():
    "Holds and manipulates a row of a table"
    def __init__(self):
        self.data = dict()
    def add(self, name, value):
        self.data[name]=value
    def get(self, name):
        return self.data[name]
    def getHtml(self):
        "Generate html code for a table raw"
        HtmlRow="<tr>"
        for a,  b in self.data.iteritems():
            HtmlRow +="<td>" +  str(b) +  "</td>"
        HtmlRow+="</tr>"
        return HtmlRow

class AbsTable():
    "table class"
    def __init__(self):
        "storage init"
        self.LastKey = -1
        self.data = dict()
    def genKey(self):
        "Generates new unique key."
        self.LastKey += 1
        return self.LastKey
    def add(self, rec):
        "Adds record raw to the table"
        self.data[self.genKey()] = rec
    def find(self, col, val):
        "search for value in a column, return list of keys or indexes"
        pass
    
    def exportText(self, FileName="data/export.tbl"):
        "Export to a text file."
        self.Fsep="\t"
        f = open(FileName, 'w')
        #rowstr=""
        hstr=""
        hflag=0
        for k, v in self.data.iteritems():
            rowstr=""
            for h, d in v.data.iteritems():
                if hflag==0:
                    hstr+=str(h)+self.Fsep
                rowstr+=str(d)+self.Fsep
            if hflag==0:
                hstr+="\n"
            hflag=1
            hstr+=rowstr+"\n"
        f.write(hstr)
        f.close()
        
    def importText(self, FileName="data/events.tbl"):
        f = open(FileName, 'r')
        table = f.read()
        table = re.split('\n', table)
        t = list()
        for L in table:
            t.append( re.split('[\t]+', L) )
        Headings = t[0]
        del t[0]
        #t now contains the table
        for row in t:
            r=AbsRecord()
            i=0
            for v in row:
                r.add(Headings[i], v)
                #print Headings[i], '\t',  v
                i+=1
            self.add(r)
''''        for a,  b in self.data.iteritems():
            s=str(a)+'\t'
            for c, d in b.data.iteritems():
                 s+=str(d)+'\t'
            s+='\n'
            print s
'''

